package com.amir.common.utils

import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

object IMEUtil {
    fun showIME(context: Context, v: View?) {
        val imm = context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.showSoftInput(v, 0)
    }

    fun hideIME(context: Context, v: View) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(v.windowToken, 0)
    }

    fun fixInputMethod(context: Context?) {
        if (context == null) {
            return
        }
        var inputMethodManager: InputMethodManager? = null
        try {
            inputMethodManager =
                context.applicationContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        } catch (th: Throwable) {
            th.printStackTrace()
        }
        if (inputMethodManager == null) {
            return
        }
        val strArr = arrayOf(
            "mCurRootView", "mServedView", "mNextServedView",
            "mLastSrvView"
        )
        for (i in 0..3) {
            try {
                val declaredField =
                    inputMethodManager.javaClass.getDeclaredField(strArr[i]) ?: continue
                if (!declaredField.isAccessible) {
                    declaredField.isAccessible = true
                }
                val obj = declaredField[inputMethodManager] as? View ?: continue
                if (obj.context === context || i == 3) {
                    declaredField[inputMethodManager] = null
                }
            } catch (th: Throwable) {
            }
        }
    }
}